package com.histone.lilian.config;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ArrayUtil;
import org.springframework.stereotype.Component;
import org.ssssssss.magicapi.modules.db.inteceptor.NamedTableInterceptor;
import org.ssssssss.magicapi.modules.db.model.SqlMode;
import org.ssssssss.magicapi.modules.db.table.NamedTable;

import java.util.Date;

/**
 * 自动注入
 */
@Component
public class AutoFillInterceptor implements NamedTableInterceptor {

    // 不自动注入
    private static String[] whiteList = {
        "sys_role_menu",
        "sys_user_role",
        "sys_user_post",
        "sys_logininfor",
        "sys_job_log",
        "sys_oper_log"
    };

    /*
     * 执行单表操作之前
     */
    @Override
    public void preHandle(SqlMode sqlMode, NamedTable namedTable) {
        if (ArrayUtil.contains(whiteList, namedTable.getTableName())) {
            return;
        }
        switch (sqlMode) {
            case INSERT:
                namedTable.column("create_by", StpUtil.getSession(true).getString("username"));
                namedTable.column("create_time", new Date());
                break;
            case UPDATE:
                namedTable.column("update_by", StpUtil.getSession(true).getString("username"));
                namedTable.column("update_time", new Date());
                break;
        }

    }
}
